/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2024 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
#include "can.h"
#include "dma.h"
#include "iwdg.h"
#include "rtc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "CRC16_MODBUS.h"
#include "msg_list.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
volatile uint8_t g_rs232_rx_state = 0;
volatile uint8_t g_rs232_rx_buf[RS232_RX_DATA_LENGTH] = {0};

volatile uint8_t g_rs485_c1_state = 0; // 0 idle 1 receiving 2 decoding 3 sending
volatile uint8_t g_rs485_c1_tx_buf[RS485_C1_TX_DATA_LENGTH] = {0};
volatile uint8_t g_rs485_c1_rx_buf[RS485_C1_RX_DATA_LENGTH] = {0};

volatile uint8_t g_rs485_c2_state = 0; // 0 idle 1 sending 2 receiving
volatile uint8_t g_rs485_c2_tx_buf[RS485_C2_TX_DATA_LENGTH] = {0};
volatile uint8_t g_rs485_c2_rx_buf[RS485_C2_RX_DATA_LENGTH] = {0};

CAN_TxHeaderTypeDef g_can_tx_message_head;
volatile uint8_t g_can_tx_data[8] = {0};
CAN_RxHeaderTypeDef g_can_rx_message_head;
volatile uint8_t g_can_rx_data[8] = {0};

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP */
void RS232_RxEventCallBack(UART_HandleTypeDef *huart, uint16_t Pos);

void RS485_C1_TxCpltCallback(UART_HandleTypeDef *huart);
void RS485_C1_RxEventCallBack(UART_HandleTypeDef *huart, uint16_t Pos);

void RS485_C2_TxCpltCallback(UART_HandleTypeDef *huart);
void RS485_C2_RxEventCallBack(UART_HandleTypeDef *huart, uint16_t Pos);

void CAN_Filter_Config(void);
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{

  /* USER CODE BEGIN 1 */
  __HAL_DBGMCU_FREEZE_IWDG();
  __HAL_DBGMCU_FREEZE_WWDG();
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  MX_RTC_Init();
  MX_IWDG_Init();
  MX_CAN_Init();
  MX_TIM4_Init();
  /* USER CODE BEGIN 2 */
  HAL_UART_RegisterRxEventCallback(&huart1, RS232_RxEventCallBack);

  HAL_UART_RegisterCallback(&huart3, HAL_UART_TX_COMPLETE_CB_ID, RS485_C1_TxCpltCallback);
  HAL_UART_RegisterRxEventCallback(&huart3, RS485_C1_RxEventCallBack);
  RS485_Status_Set(RS485_CH1, RS485_READ);

  HAL_UART_RegisterCallback(&huart2, HAL_UART_TX_COMPLETE_CB_ID, RS485_C2_TxCpltCallback);
  HAL_UART_RegisterRxEventCallback(&huart2, RS485_C2_RxEventCallBack);
  RS485_Status_Set(RS485_CH2, RS485_WRITE);

  CAN_Filter_Config();
  HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING);
  HAL_CAN_Start(&hcan);
  HAL_CAN_RegisterCallback(&hcan, HAL_CAN_RX_FIFO0_MSG_PENDING_CB_ID, HAL_CAN_RxFifo0MsgPendingCallback);

  HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1);
  /* USER CODE END 2 */

  /* Init scheduler */
  osKernelInitialize();

  /* Call init function for freertos objects (in cmsis_os2.c) */
  MX_FREERTOS_Init();

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
   * in the RCC_OscInitTypeDef structure.
   */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
   */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC;
  PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void RS232_RxEventCallBack(UART_HandleTypeDef *huart, uint16_t Pos)
{
  HAL_UART_RxEventTypeTypeDef event_type = 3; // set a invalid value temp
  Rangefinder_Msg msg_temp;

  event_type = HAL_UARTEx_GetRxEventType(huart);
  switch (event_type)
  {
  case HAL_UART_RXEVENT_TC:
    msg_temp.addr = g_rs232_rx_buf[0];
    msg_temp.func_code = g_rs232_rx_buf[1];
    msg_temp.data_len = g_rs232_rx_buf[2];
    for (uint8_t i = 0; i < 4; i++)
    {
      msg_temp.data[i] = g_rs232_rx_buf[i + 3];
    }
    msg_temp.crc_l = g_rs232_rx_buf[7];
    msg_temp.crc_h = g_rs232_rx_buf[8];
    Rangefinder_Msg_Add(&msg_temp);
    HAL_GPIO_TogglePin(LED_3_GPIO_Port, LED_3_Pin);
    g_rs232_rx_state = 0;
    break;
  case HAL_UART_RXEVENT_HT:
    /* code */
    break;
  case HAL_UART_RXEVENT_IDLE:
    g_rs232_rx_state = 0;
    break;

  default:
    break;
  }
}

void RS485_C1_TxCpltCallback(UART_HandleTypeDef *huart)
{
  RS485_Status_Set(RS485_CH1, RS485_READ);
  g_rs485_c1_state = 0;
}

void RS485_C1_RxEventCallBack(UART_HandleTypeDef *huart, uint16_t Pos)
{
  HAL_UART_RxEventTypeTypeDef event_type = 3; // set a invalid value temp
  Ctrl_Com_Msg msg_temp;
	
	event_type = HAL_UARTEx_GetRxEventType(huart);
  switch (event_type)
  {
  case HAL_UART_RXEVENT_TC:
    RS485_Status_Set(RS485_CH1, RS485_READ);
    g_rs485_c1_state = 0;
    break;
  case HAL_UART_RXEVENT_HT:
    /* code */
    break;
  case HAL_UART_RXEVENT_IDLE:
    if (g_rs485_c1_rx_buf[0] == CTRL_MSG_HEAD_1 && g_rs485_c1_rx_buf[1] == CTRL_MSG_HEAD_2)
    {
      msg_temp.head_1 = g_rs485_c1_rx_buf[0];
      msg_temp.head_2 = g_rs485_c1_rx_buf[1];
      msg_temp.src_id = g_rs485_c1_rx_buf[2];
      msg_temp.dst_id = g_rs485_c1_rx_buf[3];
      msg_temp.func_code = g_rs485_c1_rx_buf[4];
      msg_temp.data_len = g_rs485_c1_rx_buf[5];
      for (uint8_t i = 0; i < msg_temp.data_len; i++)
      {
        msg_temp.data[i] = g_rs485_c1_rx_buf[i + 6];
      }
      msg_temp.check = g_rs485_c1_rx_buf[msg_temp.data_len + 6];
      msg_temp.tail_1 = g_rs485_c1_rx_buf[msg_temp.data_len + 7];
      msg_temp.tail_2 = g_rs485_c1_rx_buf[msg_temp.data_len + 8];
      Ctrl_Rx_Msg_Add(&msg_temp);
      g_rs485_c1_state = 2;
      HAL_GPIO_TogglePin(LED_3_GPIO_Port, LED_3_Pin);
    }
    else
    {
      RS485_Status_Set(RS485_CH1, RS485_READ);
      g_rs485_c1_state = 0;
    }
    break;

  default:
    break;
  }
}

void RS485_C2_TxCpltCallback(UART_HandleTypeDef *huart)
{
  RS485_Status_Set(RS485_CH2, RS485_READ);
  if (HAL_UARTEx_ReceiveToIdle_DMA(huart, (uint8_t *)g_rs485_c2_rx_buf, RS485_C2_RX_DATA_LENGTH) == HAL_OK)
  {
    g_rs485_c2_state = 2;
  }
}

void RS485_C2_RxEventCallBack(UART_HandleTypeDef *huart, uint16_t Pos)
{
  HAL_UART_RxEventTypeTypeDef event_type = 3; // set a invalid value temp
  TDLAS_Rx_Msg msg_temp;

  event_type = HAL_UARTEx_GetRxEventType(huart);
  switch (event_type)
  {
  case HAL_UART_RXEVENT_TC:
    RS485_Status_Set(RS485_CH2, RS485_WRITE);
    g_rs485_c2_state = 0;
    break;
  case HAL_UART_RXEVENT_HT:
    /* code */
    break;
  case HAL_UART_RXEVENT_IDLE:
    msg_temp.addr = g_rs485_c2_rx_buf[0];
    msg_temp.func_code = g_rs485_c2_rx_buf[1];
    if (0x03 == msg_temp.func_code)
    {
      msg_temp.data_len = g_rs485_c2_rx_buf[2];
      for (uint8_t i = 0; i < msg_temp.data_len; i++)
      {
        msg_temp.data[i] = g_rs485_c2_rx_buf[i + 3];
      }
      msg_temp.crc_l = g_rs485_c2_rx_buf[msg_temp.data_len + 3];
      msg_temp.crc_h = g_rs485_c2_rx_buf[msg_temp.data_len + 4];
    }
    else if (0x10 == msg_temp.func_code)
    {
      msg_temp.reg_addr = (g_rs485_c2_rx_buf[3] & 0x00FF);
      msg_temp.reg_addr |= (g_rs485_c2_rx_buf[2] << 8);
      msg_temp.reg_cnt = (g_rs485_c2_rx_buf[5] & 0x00FF);
      msg_temp.reg_cnt |= (g_rs485_c2_rx_buf[4] << 8);
      msg_temp.crc_l = g_rs485_c2_rx_buf[6];
      msg_temp.crc_h = g_rs485_c2_rx_buf[7];
    }
    TDLAS_Rx_Msg_Add(&msg_temp);
    RS485_Status_Set(RS485_CH2, RS485_WRITE);
    g_rs485_c2_state = 0;
    HAL_GPIO_TogglePin(LED_3_GPIO_Port, LED_3_Pin);
    break;

  default:
    break;
  }
}

void RS485_Status_Set(RS485_Channel ch, RS485_Status status)
{
  if (status == RS485_READ)
  {
    switch (ch)
    {
    case RS485_CH1:
      HAL_GPIO_WritePin(RS485_1_DE_GPIO_Port, RS485_1_DE_Pin, GPIO_PIN_RESET);
      HAL_GPIO_WritePin(RS485_1_RE_GPIO_Port, RS485_1_RE_Pin, GPIO_PIN_RESET);
      break;
    case RS485_CH2:
      HAL_GPIO_WritePin(RS485_2_DE_GPIO_Port, RS485_2_DE_Pin, GPIO_PIN_RESET);
      HAL_GPIO_WritePin(RS485_2_RE_GPIO_Port, RS485_2_RE_Pin, GPIO_PIN_RESET);
      break;

    default:
      break;
    }
  }
  else if (status == RS485_WRITE)
  {
    switch (ch)
    {
    case RS485_CH1:
      HAL_GPIO_WritePin(RS485_1_DE_GPIO_Port, RS485_1_DE_Pin, GPIO_PIN_SET);
      HAL_GPIO_WritePin(RS485_1_RE_GPIO_Port, RS485_1_RE_Pin, GPIO_PIN_SET);
      break;
    case RS485_CH2:
      HAL_GPIO_WritePin(RS485_2_DE_GPIO_Port, RS485_2_DE_Pin, GPIO_PIN_SET);
      HAL_GPIO_WritePin(RS485_2_RE_GPIO_Port, RS485_2_RE_Pin, GPIO_PIN_SET);
      break;

    default:
      break;
    }
  }
  else
  {
    return;
  }
}

void CAN_Filter_Config(void)
{
  CAN_FilterTypeDef sFilterConfig;
  sFilterConfig.FilterBank = 0;
  sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;
  sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;
  sFilterConfig.FilterIdHigh = 0x0000;
  sFilterConfig.FilterIdLow = 0x0000;
  sFilterConfig.FilterMaskIdHigh = 0x0000;
  sFilterConfig.FilterMaskIdLow = 0x0000;
  sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0;
  sFilterConfig.FilterActivation = ENABLE;
  sFilterConfig.SlaveStartFilterBank = 14;

  if (HAL_CAN_ConfigFilter(&hcan, &sFilterConfig) != HAL_OK)
  {
    /* Filter configuration Error */
    Error_Handler();
  }
}

void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{
  HAL_StatusTypeDef status = HAL_TIMEOUT;
  Motor_Rx_Ctrl_Msg motor_rx_msg_temp;

  status = HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &g_can_rx_message_head, (uint8_t *)g_can_rx_data);
  if (status == HAL_OK)
  {
    motor_rx_msg_temp.head.StdId = g_can_rx_message_head.StdId;
    motor_rx_msg_temp.head.ExtId = g_can_rx_message_head.ExtId;
    motor_rx_msg_temp.head.IDE = g_can_rx_message_head.IDE;
    motor_rx_msg_temp.head.RTR = g_can_rx_message_head.RTR;
    motor_rx_msg_temp.head.DLC = g_can_rx_message_head.DLC;
    motor_rx_msg_temp.head.Timestamp = g_can_rx_message_head.Timestamp;
    motor_rx_msg_temp.head.FilterMatchIndex = g_can_rx_message_head.FilterMatchIndex;
    for (uint8_t i = 0; i < 8; i++)
    {
      motor_rx_msg_temp.data[i] = g_can_rx_data[i];
    }
    Motor_Rx_Msg_Add(&motor_rx_msg_temp);
  }
}
/* USER CODE END 4 */

/**
 * @brief  Period elapsed callback in non blocking mode
 * @note   This function is called  when TIM2 interrupt took place, inside
 * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
 * a global variable "uwTick" used as application time base.
 * @param  htim : TIM handle
 * @retval None
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM2)
  {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
